import React, { useEffect, useState, useMemo } from 'react';
import _ from 'lodash';
import { nanoid } from 'nanoid';
import { Button, Drawer, Empty, message, Spin, Tree } from 'antd';
import DebounceWrapper from '@/components/DebounceWrapper';
import { fetchDepartmentList } from '@/services/system/department';
import { fetchJobDepartmentRelation, updateJobDepartmentRelation } from '@/services/system/job';
import { formatTree } from '@/utils/utils';
import styles from './jobDepartmentRelationDrawer.less';

const DebounceButton = DebounceWrapper(Button);
const getNodeIds = (tree = [], arr = []) => {
  if (!tree.length) return [];
  _.forEach(tree, (item) => {
    if (item.children && item.children.length) {
      arr.push(item.key);
      getNodeIds(item.children, arr);
    } else {
      arr.push(item.key);
    }
  });
  return arr;
};

export default ({ visible, jobId, closeDrawer }) => {
  const [initialLoading, setInitialLoading] = useState(true);
  const [departmentTree, setDepartmentTree] = useState([]);
  const [relationLoadingId, setRelationLoadingId] = useState('');
  const [checkedKeys, setCheckedKeys] = useState([]);
  const [actionLoading, setActionLoading] = useState(false);

  const validDepartmentIds = useMemo(() => getNodeIds(departmentTree), [departmentTree]);

  // 获取机构节点列表
  const getOrganTree = async () => {
    try {
      const res = await fetchDepartmentList({ size: -1, current: 1 });
      return _.isArray(res)
        ? formatTree(res, ({ organName, id, address }) => ({
            key: id,
            title: organName,
            description: address || '',
          }))
        : [];
    } catch (e) {
      return [];
    }
  };
  // 获取岗位关联的机构列表
  const getJobDepartmentRelation = async (postId) => {
    try {
      const res = await fetchJobDepartmentRelation({ postId });
      return _.isArray(res) ? res : [];
    } catch (e) {
      return [];
    }
  };

  // 初始化
  useEffect(() => {
    getOrganTree().then((treeData) => {
      setDepartmentTree(treeData);
      setInitialLoading(false);
    });
  }, []);
  useEffect(() => {
    if (!_.isEmpty(departmentTree)) {
      if (visible) {
        const nextRelationLoadingId = nanoid(12);
        setRelationLoadingId(nextRelationLoadingId);
        getJobDepartmentRelation(jobId).then((checkedIds) => {
          let validDataFetch;
          setRelationLoadingId((currentId) => {
            if (currentId === nextRelationLoadingId) {
              validDataFetch = true;
              return '';
            }
            return currentId;
          });
          if (validDataFetch) {
            // 排除机构节点删除之前授权的id
            const nextCheckedKeys = _.filter(checkedIds, (id) =>
              _.includes(validDepartmentIds, id),
            );
            setCheckedKeys(nextCheckedKeys);
          }
        });
        return;
      }
      setCheckedKeys([]);
      setRelationLoadingId('');
    }
  }, [visible, departmentTree]);

  // 交互勾选（父子节点不关联）
  const handleCheck = ({ checked }) => {
    setCheckedKeys(checked);
  };

  const handleCancel = () => {
    if (!actionLoading) {
      closeDrawer();
    }
  };
  const handleConfirm = () => {
    setActionLoading(true);
    const params = { postId: jobId, organList: checkedKeys };
    updateJobDepartmentRelation(params)
      .then(() => {
        closeDrawer();
        setActionLoading(false);
        message.success('岗位机构关联关系更新成功');
      })
      .catch(() => {
        setActionLoading(false);
      });
  };

  return (
    <Drawer
      visible={visible}
      title={
        <div className={styles.drawerTitle}>
          岗位关联机构
          <div className={styles.drawerSubTitle}>
            岗位可关联给任意机构节点(机构父子节点不再关联)
          </div>
        </div>
      }
      bodyStyle={{ paddingBottom: 80 }}
      onClose={handleCancel}
      footer={
        <div className={styles.drawerFooterButtonContainer}>
          <DebounceButton
            disabled={actionLoading}
            onClick={handleCancel}
            style={{ marginRight: 8 }}
          >
            取消
          </DebounceButton>
          <DebounceButton
            onClick={handleConfirm}
            type="primary"
            loading={actionLoading}
            disabled={initialLoading || !!relationLoadingId}
          >
            确定
          </DebounceButton>
        </div>
      }
    >
      <Spin spinning={initialLoading || !!relationLoadingId} tip="加载中...">
        {departmentTree.length ? (
          <Tree
            checkable
            checkStrictly
            defaultExpandAll
            treeData={departmentTree}
            onCheck={handleCheck}
            checkedKeys={checkedKeys}
            titleRender={({ key, title, description }) => {
              return (
                <span key={key} title={description} className={styles.treeNodeTitle}>
                  <span className={styles.treeNodeTitleText}>{title}</span>
                </span>
              );
            }}
          />
        ) : (
          <Empty description={'暂无数据'} />
        )}
      </Spin>
    </Drawer>
  );
};
